package bid.yanhj.yanhaijiang.baseadapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class MainAdapter extends BaseAdapter {
    // 把数据类放到Adapter
    private List<Person> persons;
    // 通过构造方法传进来
    public MainAdapter(List<Person> persons) {
        this.persons = persons;
    }

    /**
     * 共多少
     * @return
     */
    @Override
    public int getCount() {
        return persons == null? 0 : persons.size();
    }

    /**
     * 返回每一行的数据类
     * @param position
     * @return
     */
    @Override
    public Person getItem(int position) {
        return persons.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    /**
     * 3 配置getView方法
     * 返回我行布局每一个View
     * @param position
     * @param convertView
     * @param parent
     * @return
     */
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;

        if (convertView == null) {
            Context context = parent.getContext();
            // 注入行布局
            convertView = LayoutInflater.from(context)
                    .inflate(R.layout.item_main, parent, false);

            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else  {
            // 行布局不为空操作
            viewHolder = (ViewHolder) convertView.getTag();
        }

        // 对view 各种组件设置数据
//        ImageView imageView = convertView.findViewById(R.id.item_icon);
//        imageView.setImageResource(persons.get(position).getIcon());
//
//        TextView textView = convertView.findViewById(R.id.item_name);
//        textView.setText(persons.get(position).getName());

        viewHolder.imageView.setImageResource(persons.get(position).getIcon());
        viewHolder.textView.setText(persons.get(position).getName());

        return convertView;
    }

    // 更新数据
    public void deletePos (int pos) {
        persons.remove(pos);
        notifyDataSetChanged();
    }

    private class ViewHolder {
        ImageView imageView;
        TextView textView;

        public ViewHolder(View itemView) {
            imageView = (ImageView)itemView.findViewById(R.id.item_icon);
            textView = (TextView)itemView.findViewById(R.id.item_name);
        }
    }
}
